package at.ac.tuwien.dse.health.admin.jdbc

import java.sql.ResultSet
import scala.collection.mutable.ListBuffer

/** Contains utility methods for [[at.ac.tuwien.dse.health.admin.jdbc.RowMapper]]. */
object RowMapper {
	/** Creates a [[at.ac.tuwien.dse.health.admin.jdbc.RowMapper]] from the given mapping function. */
	def apply[T](map: (ResultSet, Int) => T) = new RowMapper[T] {
		def mapRow(rs: ResultSet, rowNum: Int): T = map(rs, rowNum)
	}
}

/** Maps [[java.sql.ResultSet]] to custom object. */
trait RowMapper[T] {
	/** Maps the current row of the given [[java.sql.ResultSet]] with row ID `rowNum`. */
	def mapRow(rs: ResultSet, rowNum: Int): T

	/** Maps all rows of the given [[java.sql.ResultSet]]. */
	def mapRows(rs: ResultSet) = {
		val list: ListBuffer[T] = ListBuffer[T]()
		while (rs.next) list += mapRow(rs, list.length)
		list.toList
	}
}

/** Extracts the first column of every row and converts it to the desired type. */
class SimpleRowMapper[T](col: Int = 1) extends RowMapper[T] {
	def mapRow(rs: ResultSet, rowNum: Int): T = (rs getObject col).asInstanceOf[T]
}

class ListRowMapper extends RowMapper[List[_]] {
	def mapRow(rs: ResultSet, rowNum: Int): List[_] = (for {i <- (1 to rs.getMetaData.getColumnCount)} yield rs.getObject(i)).toList
}
